package com.summer.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.summer.entity.*;
import com.summer.mapper.*;
import com.summer.service.IOrderCollectionService;
import com.summer.util.BuildXLSX;
import com.summer.util.CallBackResult;
import com.summer.util.XlsxParam;
import com.summer.variable.Constant;
import com.summer.vo.CollectionUserVO;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

/**
 * Desc:
 * Created by tl on 2019/1/4
 */
@Controller
@RequestMapping("/v1.0/api/collectOrder")
public class OrderCollectionController {
    private static Logger log = LoggerFactory.getLogger(OrderCollectionController.class);
    @Resource
    private OrderCollectionDAO orderCollectionDAO;
    @Resource
    private OrderRepaymentMapper orderRepaymentMapper;
    @Resource
    private OrderCollectionReductionDAO orderCollectionReductionDAO;

    @Resource
    private IOrderCollectionService orderCollectionService;
    @Resource
    private OrderCollectionDetailDAO orderCollectionDetailDAO;
    @Resource
    private OrderRepaymentDetailDAO orderRepaymentDetailDAO;

    /**
     * 催收订单列表
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/queryWithUser")
    public String queryWithUser(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderCollectionController queryWithUser params=" + params.toString());
        PageHelper.startPage(params);
        List<CollectionUserVO> list = orderCollectionDAO.findParams(params);
        return CallBackResult.returnJson(new PageInfo<>(list));
    }

    /**
     * 催收详情
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/detail")
    public String detail(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderCollectionController detail params=" + params.toString());
        OrderCollection orderCollection = checkId(params);
        if (null == orderCollection)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        Map<String, Object> map = new HashMap<String, Object>(4) {{
            put("collectionId", orderCollection.getId());
            put("auditStatus", Constant.COLLECTION_AUDIT_PASS);
            put("repaymentId", orderCollection.getRepaymentId());
            put("status", Constant.REPAYMENTDETAIL_STATUS_PAID);
        }};
        List<OrderCollectionReduction> orderCollectionReductions = orderCollectionReductionDAO.selectSimple(map);
        List<CollectionUserVO> list = new ArrayList<>();
        StringBuilder sb = null;
        if (CollectionUtils.isNotEmpty(orderCollectionReductions)) {
            for (OrderCollectionReduction orderCollectionReduction : orderCollectionReductions) {
                sb = new StringBuilder();
                //TODO 催收员
                CollectionUserVO collectionUserVO =
                        new CollectionUserVO(orderCollection.getCurrentCollectionUserId() + "",
                                orderCollectionReduction.getCreateTimeChg(), "减免滞纳金",
                                sb.append("减免").append(orderCollectionReduction.getReductionAmount()).toString());
                list.add(collectionUserVO);
                sb=null;
            }
        }
        List<OrderCollectionDetail> orderCollectionDetails = orderCollectionDetailDAO.selectSimple(map);
        if (CollectionUtils.isNotEmpty(orderCollectionDetails)) {
            for (OrderCollectionDetail orderCollectionDetail : orderCollectionDetails) {
                sb = new StringBuilder();
                String collectionType = "";
                if (Constant.COLLECTION_TYPE_PHONE == orderCollectionDetail.getCollectionType()) {
                    collectionType = "电话催收";
                } else if (Constant.COLLECTION_TYPE_MSG == orderCollectionDetail.getCollectionType()) {
                    collectionType = "短信催收";
                }
                //TODO 催收员
                CollectionUserVO collectionUserVO =
                        new CollectionUserVO(orderCollection.getCurrentCollectionUserId() + "",
                                orderCollectionDetail.getCreateTimeChg(), "催收记录",
                                sb.append(collectionType).append(orderCollectionDetail.getCollectionTag()).append("-").append(orderCollection.getPromiseRepaymentTimeChg()).append("-").append(orderCollectionDetail.getRemark()).toString());
                list.add(collectionUserVO);
                sb=null;
            }
        }
        List<OrderRepaymentDetail> orderRepaymentDetails = orderRepaymentDetailDAO.selectSimple(map);
        if (CollectionUtils.isNotEmpty(orderRepaymentDetails)) {
            for (OrderRepaymentDetail orderRepaymentDetail : orderRepaymentDetails) {
                sb = new StringBuilder();
                //TODO 催收员
                CollectionUserVO collectionUserVO =
                        new CollectionUserVO(orderCollection.getCurrentCollectionUserId() + "",
                                orderRepaymentDetail.getCreateTimeChg(),
                                Constant.PAY_TYPE_MAP.get(orderRepaymentDetail.getPayType())+"还款",
                                sb.append("已还").append(orderRepaymentDetail.getPaidAmount()).toString());
                list.add(collectionUserVO);
                sb=null;
            }
        }
        return CallBackResult.returnJson(new PageInfo<>(list));
    }

    /**
     * 减免操作
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/reduce")
    public String reduce(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderCollectionController reduce params=" + params.toString());
        OrderCollection orderCollection = checkId(params);
        if (null == orderCollection)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        Map<String, Object> map = new HashMap<String, Object>(4) {{
            put("collectionId", orderCollection.getId());
        }};
        List<OrderCollectionReduction> orderCollectionReductions = orderCollectionReductionDAO.selectSimple(map);
        if (CollectionUtils.isNotEmpty(orderCollectionReductions)) {
            OrderCollectionReduction orderCollectionReduction = orderCollectionReductions.get(0);
            if (orderCollectionReduction != null && Constant.COLLECTION_AUDIT_TODO ==
                    orderCollectionReduction.getAuditStatus()) {
                return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "已有减免申请在审核中,勿重复申请");
            }
        }
        OrderRepayment orderRepayment = orderRepaymentMapper.selectByPrimaryKey(orderCollection.getRepaymentId());
        Object reductionAmountObj = params.get("reductionAmount");
        if (null == reductionAmountObj)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        int reductionAmount = Integer.parseInt(reductionAmountObj.toString());
        if (reductionAmount <= 0 || reductionAmount > (orderRepayment.getLateFee() - orderCollection.getReductionMoney()) * 100)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "还款金额必须大于0且不大于滞纳金");
        orderCollectionService.reduce(params, orderCollection, reductionAmount);
        return CallBackResult.returnJson("操作成功");
    }

    /**
     * 催收登记
     *
     * @param jsonData
     * @return
     */
    @ResponseBody
    @PostMapping("/addCollection")
    public String addCollection(@RequestBody String jsonData) {
        Map<String, Object> params = JSONObject.parseObject(jsonData);
        log.info("OrderCollectionController addCollection params=" + params.toString());
        OrderCollection orderCollection = checkId(params);
        if (null == orderCollection)
            return CallBackResult.returnJson(CallBackResult.BUSINESS_ERROR, "参数非法");
        orderCollectionService.addDetail(params, orderCollection);
        return CallBackResult.returnJson("操作成功");
    }

    private OrderCollection checkId(Map<String, Object> params) {
        Object idObj = params.get("id");
        if (null == idObj) {
            return null;
        }
        return orderCollectionDAO.selectByPrimaryKey(Integer.parseInt(idObj.toString()));
    }

    /**
     * 导出催收订单列表
     *
     * @param request
     * @param response
     * @param params
     * @throws Exception
     */
    @RequestMapping("downloadOrderCollect")
    public void downloadOrderCollect(HttpServletRequest request, HttpServletResponse response,
                                     @RequestParam Map<String, Object> params) throws Exception {
        log.info("OrderCollectionController downloadOrderCollect params=" + params.toString());
        List<CollectionUserVO> list = orderCollectionDAO.findParams(params);
        log.info("OrderCollectionController downloadOrderCollect size=" + list.size());
        String title = "催收订单列表";
        BuildXLSX.setFileDownloadHeader(request, response, title);
        LinkedHashMap<String, String> titleMap = new LinkedHashMap<>();
        titleMap.put("realName", "客户姓名");
        titleMap.put("phone", "手机号码");
        titleMap.put("applyAmount", "借款金额");

        titleMap.put("loanTerm", "借款期限");
        titleMap.put("principalAmount", "应还金额");
        titleMap.put("lateFee", "滞纳金");

        titleMap.put("paidAmount", "已还金额");
        titleMap.put("loanTimeChg", "放款日期");
        titleMap.put("repaymentTimeChg", "预计还款日期");
        titleMap.put("lateDay", "逾期天数");
        titleMap.put("groupLevel", "催收小组");
        titleMap.put("userName", "催收人员");
        titleMap.put("overdueCount", "逾期次数");
        titleMap.put("payStatus", "逾期状态");
        titleMap.put("payType", "还款方式");
        XlsxParam xlsxParam = new XlsxParam(list, title, titleMap);
        OutputStream os = response.getOutputStream();
        BuildXLSX.buildExcel(xlsxParam, os);
    }
}
